package com.demo.juc.util;

import java.util.concurrent.Semaphore;

/**
 * @Author: jxm
 * @Description: 信号量 例子：抢停车位
 * @Date: 2024-2-5 16:26
 * @Version: 1.0
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        //模拟三个车位
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"\t抢到车位了");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"离开车位");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf("线程"+i)).start();
        }
    }
}
